package com.ddstation.weather.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.ddstation.common.property.EnvironmentEnum;
import com.ddstation.common.property.EnvironmentProperties;
import com.ddstation.crud.entity.MaInvsWeatherEntity;
import com.ddstation.crud.mapper.MaInvsWeatherMapper;
import com.ddstation.weather.model.Daily_forecast;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class WeatherServiceImpl implements WeatherService {
	
	// 查询天气数据
	public Daily_forecast getWeather(String weatherLocation){
		// 测试环境用测试环境的天气key
	    String param = "key=ce4b24df6ab649f0a1470194e773f6fa&location="+weatherLocation;
	    
	    if (EnvironmentProperties.getEnvType() != EnvironmentEnum.DEV){// 生产环境调商业版本的url
	    	param = "key=b538ff27cdb0431bbe21dd9182533258&location="+weatherLocation;
	    }
	    
	    StringBuilder sb = new StringBuilder();
	    InputStream is = null;
	    BufferedReader br = null;
	    PrintWriter out = null;
	    Daily_forecast weather = null;
	    try {
	        //接口地址
	        String url = "https://free-api.heweather.net/s6/weather";
	        if (EnvironmentProperties.getEnvType() != EnvironmentEnum.DEV){// 生产环境调商业版本的url
	        	url = "https://api.heweather.net/s6/weather";
	        }
	        URL uri = new URL(url);
	        HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
	        connection.setRequestMethod("POST");
	        connection.setReadTimeout(5000);
	        connection.setConnectTimeout(10000);
	        connection.setRequestProperty("accept", "*/*");
	        //发送参数
	        connection.setDoOutput(true);
	        out = new PrintWriter(connection.getOutputStream());
	        out.print(param);
	        out.flush();
	        //接收结果
	        is = connection.getInputStream();
	        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String line;
	        //缓冲逐行读取
	        while ( ( line = br.readLine() ) != null ) {
	            sb.append(line);
	        }
	        JSONObject jsonobject = JSONObject.fromObject(sb.toString());//字符串转成对象
	        JSONArray jsonArray = jsonobject.getJSONArray("HeWeather6");
	        JSONArray nowArray = jsonArray.getJSONObject(0).getJSONArray("daily_forecast");
	        
	        JSONObject nowObject = nowArray.getJSONObject(0);
	        
	        weather = (Daily_forecast)JSONObject.toBean(nowObject,Daily_forecast.class);
	        // 白天天气取得
	        MaInvsWeatherEntity a = maInvsWeatherMapper.selectByPrimaryKey(weather.getCond_code_d()); 
	        if (a==null){
	        	throw new RuntimeException("天气图标查询失败：返回值"+weather.toString());
	        }
	        weather.setWeatherIconUrl("https://wenuan-static.oss-cn-shanghai.aliyuncs.com/icon/pc/weather/"+a.getPhotoId());
	    } catch ( Exception ignored ) {
	    	throw new RuntimeException("天气数据查询失败"+ignored.getMessage());
	    } finally {
	        //关闭流
	        try {
	            if(is!=null){
	                is.close();
	            }
	            if(br!=null){
	                br.close();
	            }
	            if (out!=null){
	                out.close();
	            }
	        } catch ( Exception ignored ) {}
	    }
	    
	    return weather;
	}
	
	@Inject private MaInvsWeatherMapper maInvsWeatherMapper;
}
